﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using CnBlogsClient.ViewModels;
using CnBlogsCore.Model;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;

namespace CnBlogsClient.Views.News
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class NewsDetailsPage : ContentPage
    {
        NewsDetailsViewModel ViewModel => vm ?? (vm = BindingContext as NewsDetailsViewModel);
        NewsDetailsViewModel vm;
        NewsDetail news;
        
        public NewsDetailsPage(CnBlogsCore.Model.News news)
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, true);
            Title = news.Title;

            this.news = new NewsDetail();
            this.news.Id = news.Id;
            this.news.Title = news.Title;
            this.news.Summary = news.Summary;
            this.news.DiggCount = news.DiggCount;
            this.news.ViewCount = news.ViewCount;
            this.news.DateAdded = news.DateAdded;

            BindingContext = new NewsDetailsViewModel(this.news);

            formsWebView.OnContentLoaded += delegate (object sender, EventArgs e)
            {
                RefreshNews();
            };
        }

        async void RefreshNews()
        {
            IsoDateTimeConverter iso = new IsoDateTimeConverter
            { DateTimeFormat = "yyyy-MM-dd" };
            var question = JsonConvert.SerializeObject(await ViewModel.RefreshNewsAsync(), iso);
            await formsWebView.InjectJavascriptAsync("updateModel(" + question + ");");
        }

        void OnReloadNews(object sender, EventArgs args)
        {
            RefreshNews();
        }
    }
}